﻿using System;
using System.Data;
using System.IO;
using System.Collections;
using System.Web.UI.WebControls;

using BLL;
using Model;
using Utility;

namespace EvaluationSystem
{
    public partial class EvaluationResult : System.Web.UI.Page
    {
        private EnterpriseUserBLL m_eUserBll = new EnterpriseUserBLL();
        private ActivityBLL m_ActivityBll = new ActivityBLL();
        private TesterInfoBLL m_TesterInfoBll = new TesterInfoBLL();        

        protected void Page_Load(object sender, EventArgs e)
        {
            ((SiteEnterpriseMaster)Master).InitMenu();
            ((SiteEnterpriseMaster)Master).li1.Attributes.Add("class", "hover ccc");
            ((SiteEnterpriseMaster)Master).b_hmenu1.Style.Clear();
            ((SiteEnterpriseMaster)Master).b_hmenu2.Style.Add("display", "none");
            ((SiteEnterpriseMaster)Master).b_hmenu3.Style.Add("display", "none");
            ((SiteEnterpriseMaster)Master).b_hmenu4.Style.Add("display", "none");
            ((SiteEnterpriseMaster)Master).s_menu1_2.Style.Add("COLOR", "#147ab8");
            ((SiteEnterpriseMaster)Master).s_menu1_2.Style.Add("TEXT-DECORATION", "none");   

            /*判断是否是企业用户身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(),
                    "PopupScript", "<script>alert('请先登录系统!');top.location.href='../Enterprise/EnterpriseLogin.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    ViewState["orderby"] = "tester_matching";
                    ViewState["asc"] = "desc";

                    if (!string.IsNullOrEmpty(Session["username"].ToString()))
                    {
                        string uid = m_eUserBll.GetEnterpriseIdByUser(Session["username"].ToString());
                        DataSet dsActivity = m_ActivityBll.GetActivityAll(uid);
                        if (dsActivity != null)
                        {
                            ddlActivity.DataSource = dsActivity.Tables[0].DefaultView;
                            ddlActivity.DataValueField = "activity_id";
                            ddlActivity.DataTextField = "activity_name";
                            ddlActivity.DataBind();
                            bind();
                        }
                    }
                }
            }
        }

        private void bind()
        {
            if (Session["EuserID"] != null)
            {
                string usrID = Session["EuserID"].ToString();
                if (!string.IsNullOrEmpty(usrID))
                {
                    string activityID = ddlActivity.SelectedValue;
                    DataSet ds = m_TesterInfoBll.GetListByEnterprise(usrID, activityID);

                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        DataView dv = ds.Tables[0].DefaultView;
                        dv.Sort = (String)ViewState["orderby"] + " " + (String)ViewState["asc"];

                        grVEvaluationResult.DataSource = dv;
                        grVEvaluationResult.DataBind();
                    }
                    else
                    {
                        grVEvaluationResult.DataSource = null;
                        grVEvaluationResult.DataBind();
                    }
                }
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //首列显示序号
            if (e.Row.RowIndex != -1)
            {
                int iRowNum = e.Row.RowIndex + 1;
                e.Row.Cells[0].Text = iRowNum.ToString();
            }

            string score = string.Empty;
            decimal n =0;
            foreach (GridViewRow gvr in grVEvaluationResult.Rows)
            {
                score = gvr.Cells[7].Text.Trim();
                if (score.IndexOf("%") == -1)
                {
                    n = Math.Round(decimal.Parse(score) * 100, 2, MidpointRounding.AwayFromZero);
                    gvr.Cells[7].Text = n.ToString() + "%";
                }
            }
        }

        protected void grVEvaluationResult_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            if (ViewState["orderby"].ToString() == sPage)
            {
                if (ViewState["asc"].ToString() == "desc")
                    ViewState["asc"] = "asc";
                else
                    ViewState["asc"] = "desc";
            }
            else
            {
                ViewState["orderby"] = e.SortExpression;
            }
            bind();
        }

        protected void ddlActivity_SelectedIndexChanged(object sender, EventArgs e)
        {
            bind();
            CB_SelectAll.Checked = false;
        }

        protected DataTable GetDimScore(string guid)
        {
            if (string.IsNullOrEmpty(guid))
            {
                return null;
            }
            else
            {
                RptBLL rptBLL = new RptBLL();
                DataTable dimTable = rptBLL.GetDimensionScore(guid);

                if (dimTable != null && dimTable.Rows.Count > 0)
                {
                    /* 2011/7/19 按照要求，保留所有维度，导出
                    //删除智力维度在维度得分表里。
                    for (int k = 0; k < dimTable.Rows.Count; k++)
                    {
                        if (dimTable.Rows[k][5].ToString().Trim().Equals("3"))//智力潜能类
                        {
                            dimTable.Rows[k].Delete();
                            dimTable.AcceptChanges();
                            k--;
                        }
                    }
                    */
                    //删除三个特殊维度在维度得分表里。
                    for (int s = 0; s < dimTable.Rows.Count; s++)
                    {
                        if (dimTable.Rows[s][1].ToString().Trim().Equals("社会称许性") ||
                            dimTable.Rows[s][1].ToString().Trim().Equals("心理健康度") ||
                            dimTable.Rows[s][1].ToString().Trim().Equals("诚信"))
                        {
                            dimTable.Rows[s].Delete();
                            dimTable.AcceptChanges();
                            s--;
                        }
                    }                     

                    for (int i = 0; i < dimTable.Rows.Count; i++)
                    {
                        int dimID = Int32.Parse(dimTable.Rows[i][0].ToString());//维度ID
                        int dimscore = Int32.Parse(dimTable.Rows[i][2].ToString());//维度原始分

                        if (dimTable.Rows[i][5].ToString().Trim().Equals("3"))//智力潜能类
                        {
                            dimTable.Rows[i][2] = rptBLL.ConvertZhiLiDimScore(dimID, dimscore);
                        }
                        else
                        {
                            dimTable.Rows[i][2] = rptBLL.ConvertDimScore(dimID, dimscore);
                        }
                    }
                    return dimTable;
                }
                else
                {
                    return null;
                }
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            ArrayList arSelList = new ArrayList();
            foreach (GridViewRow gr in grVEvaluationResult.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[1].FindControl("CB_Select");
                if (true == chk.Checked)
                {
                    arSelList.Add(grVEvaluationResult.DataKeys[gr.RowIndex].Values[0].ToString());
                }
            }

            if (arSelList.Count > 0)
            {
                string usrID = string.Empty;
                if (Session["EuserID"] != null)
                {
                    usrID = Session["EuserID"].ToString();
                }
                string activityNM = ddlActivity.SelectedItem.ToString();

                DataSet ds = m_TesterInfoBll.GetListByEnterprise(usrID, ddlActivity.SelectedValue);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    ds.Tables[0].Columns.Add("项目名称");
                    for (int k = 0; k < ds.Tables[0].Rows.Count; k++)
                    {
                        ds.Tables[0].Rows[k]["项目名称"] = activityNM;
                        string guid = ds.Tables[0].Rows[k]["tester_sn"].ToString();
                        DataTable dt = GetDimScore(guid);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            for (int j = 0; j < dt.Rows.Count; j++)
                            {
                                if (ds.Tables[0].Columns.IndexOf(dt.Rows[j]["DIMNM"].ToString()) != -1)
                                {
                                    ds.Tables[0].Rows[k][dt.Rows[j]["DIMNM"].ToString()] = dt.Rows[j]["DIMSCORE"].ToString();
                                }
                                else
                                {
                                    ds.Tables[0].Columns.Add(dt.Rows[j]["DIMNM"].ToString());
                                    ds.Tables[0].Rows[k][dt.Rows[j]["DIMNM"].ToString()] = dt.Rows[j]["DIMSCORE"].ToString();
                                }
                            }
                        }
                    }

                    ds.Tables[0].Columns["tester_sn"].ColumnName = "测试序列号";
                    ds.Tables[0].Columns["tester_email"].ColumnName = "E-Mail";
                    ds.Tables[0].Columns["tester_name"].ColumnName = "姓名";
                    ds.Tables[0].Columns["tester_sex"].ColumnName = "性别";
                    ds.Tables[0].Columns["tester_birthdate"].ColumnName = "出生日期";
                    ds.Tables[0].Columns["tester_education"].ColumnName = "学历";
                    ds.Tables[0].Columns["tester_enterprise"].ColumnName = "公司名称";
                    ds.Tables[0].Columns["tester_mobile"].ColumnName = "联系电话";
                    ds.Tables[0].Columns["tester_experience"].ColumnName = "工作年龄";
                    ds.Tables[0].Columns["tester_application"].ColumnName = "职务";
                    ds.Tables[0].Columns["tester_matching"].ColumnName = "匹配度";
                    ds.Tables[0].Columns["tester_consistencyscore"].ColumnName = "作答一致性";
                    ds.Tables[0].Columns["tester_teststarttime"].ColumnName = "测试开始时间";
                    ds.Tables[0].Columns["tester_testendtime"].ColumnName = "测试结束时间";
                    ds.Tables[0].Columns["tester_experienceinner"].ColumnName = "本店工作经验";
                    ds.Tables[0].Columns["tester_dealer"].ColumnName = "经销商名称";
                    ds.Tables[0].Columns["tester_department"].ColumnName = "部门";

                    ds.Tables[0].Columns.Remove("tester_enterpriseid");
                    ds.Tables[0].Columns["项目名称"].SetOrdinal(0);

                    //清空DBNull.Value值
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        foreach (DataColumn dc in ds.Tables[0].Columns)
                        {
                            if (dr[dc] == DBNull.Value)
                            {
                                dr[dc] = string.Empty;
                            }
                        }
                    }

                    //导出选中项
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        string sn = ds.Tables[0].Rows[i][1].ToString();
                        bool b = false;
                        for (int j = 0; j < arSelList.Count; j++)
                        {
                            if (sn.Equals(arSelList[j].ToString()))
                            {
                                b = true;
                            }
                        }
                        if (false == b)
                        {
                            ds.Tables[0].Rows[i].Delete();
                            ds.Tables[0].AcceptChanges();
                            i--;
                        }
                    }

                    //开始导出
                    string filePath = Server.MapPath("../userfiles") + @"\" +
                        activityNM + "_测评结果_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss") + ".xls";
                    string fileName = Path.GetFileName(filePath);
                    ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, ds);
                    Stream stream = null;
                    stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    long bytesToRead = stream.Length;
                    Response.Clear();
                    Response.ContentType = "application/ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                        System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));

                    while (bytesToRead > 0)
                    {
                        if (Response.IsClientConnected)
                        {
                            byte[] buffer = new Byte[10000];
                            int length = stream.Read(buffer, 0, 10000);
                            Response.OutputStream.Write(buffer, 0, length);
                            Response.Flush();
                            bytesToRead = bytesToRead - length;
                        }
                        else
                        {
                            bytesToRead = -1;
                        }
                    }
                }
            }
            else
            {
                //Response.Write("<script>alert('请选择要导出的人员!')</script>");
            }
        }

        protected void btnZipRpt_Click(object sender, EventArgs e)
        {
            ArrayList arSelList = new ArrayList();
            foreach (GridViewRow gr in grVEvaluationResult.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[1].FindControl("CB_Select");
                if (true == chk.Checked)
                {
                    arSelList.Add(grVEvaluationResult.DataKeys[gr.RowIndex].Values[0].ToString());
                }
            }
            if (arSelList.Count > 0)
            {
                Session["ExportList"] = arSelList;
                Response.Redirect("~/Report/GenPdfReport.aspx");
            }
            else
            {
                //Response.Write("<script>alert('请选择要导出的人员!')</script>");
            }            
        }

        protected void btnSelAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < grVEvaluationResult.Rows.Count; i++)
            {
                GridViewRow gr = grVEvaluationResult.Rows[i];
                CheckBox chk = (CheckBox)gr.Cells[1].FindControl("CB_Select");
                chk.Checked = CB_SelectAll.Checked; //跟随全选按扭的状态变化;
            }
        }
    }
}